package short_semester.questionnaire_planet.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.IOException;


@Service
public class QRCodeService {
    // 自定义参数，这部分是Hutool工具封装的
    
    public static String filePath = "/usr/local/nginx/html/img/";
    
    public static String suffix = ".png";
    
    public static String imgurl = "http://49.233.19.198/img/";
    
    private static QrConfig initQrConfig() {
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        config.setForeColor(Color.BLACK.getRGB());
        // 设置背景色（灰色）
        config.setBackColor(Color.WHITE.getRGB());
        return config;
    }

    /**
     * 生成到文件
     *
     */
    public String createQRCode2File(String uuid,String type) {
        String fileName = uuid+suffix;
        
        try {
            QrCodeUtil.generate(toQurl(uuid,type), initQrConfig(), FileUtil.file(filePath+fileName));
            return imgurl+fileName;
//            log.info("生成二维码成功, 位置在：{}！", filepath);
        } catch (QrCodeException e) {
            e.printStackTrace();
//            log.error("发生错误！ {}！", e.getMessage());
        }
        
        return null;
    }

    /**
     * 生成到流
     *
     * @param content
     * @param response
     */
    public void createQRCode2Stream(String content, HttpServletResponse response) {
        try {
            QrCodeUtil.generate(content, initQrConfig(), "png", response.getOutputStream());
//            log.info("生成二维码成功!");
        } catch (QrCodeException | IOException e) {
//            log.error("发生错误！ {}！", e.getMessage());
        }
    }
    
    public void removeImg(String uuid){
        String fileName = uuid+".png";
        File file = new File(filePath+fileName);
        if(file.exists()){
            file.delete();
        }
    }
    
    public String toQurl(String uuid,String type){
        if(type==null)type="";
        return "http://82.157.94.33/fill/"+type+"?questionnaireId="+uuid;
//        return "http://82.157.94.33/fill?questionnaireId="+uuid;
    }
    
    public String toImgurl(String uuid){
        String fileName = uuid+suffix;
        return imgurl+fileName;
    }
}
